package com.darren.archive.service.impl;

import com.darren.archive.mapper.SysParameterMapper;
import com.darren.archive.model.SysParameter;
import com.darren.archive.service.ISysParameterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Description: 系统参数业务层实现
 * @Author: 周金涛
 * @Date: 2019-09-18 12:38:41
 */

@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)//默认该类的所有方法都开启事务，遇到Exception就回滚
public class SysParameterServiceImpl implements ISysParameterService {

    @Resource
    private SysParameterMapper sysParameterMapper;

    /**
     * 保存系统参数
     *
     * @param record 系统参数
     * @return
     */
    @Override
    @Caching(put = {
            @CachePut(value = "systemParameter", key = "#p0.id")
    }, evict = {
            @CacheEvict(value = "systemParameter", key = "#p0.lookupCat+#p0.lookupType+#p0.enable")
    }
    )
    public SysParameter save(SysParameter record) {
        if (record != null && record.getId() == null) {
            sysParameterMapper.insert(record);
        } else if (record != null){
            sysParameterMapper.updateByPrimaryKey(record);
        }else{
            throw new ArithmeticException("参数错误，保存失败！");
        }
        return sysParameterMapper.selectByPrimaryKey(record.getId());
    }

    /**
     * 根据主建删除系统能数
     *
     * @param id
     * @return
     */
    @Override
    @CacheEvict(value = "systemParameter")
    public int deleteByPrimaryKey(Long id) {
        return sysParameterMapper.deleteByPrimaryKey(id);
    }


    /**
     * 根据主键查询系统参数
     *
     * @param id 主键ID
     * @return
     */
    @Override
    @Caching(cacheable = {@Cacheable(cacheNames = "systemParameter", key = "#id", condition = "#id != null")})
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)//不开启事务的支持
    public SysParameter findByPrimaryKey(Long id) {
        return sysParameterMapper.selectByPrimaryKey(id);
    }

    /**
     * 根据配置分类名、参数名，获取系统参数
     *
     * @param lookupCat  配置分类名
     * @param lookupType 参数名
     * @param enable     参数状态，是否启用，非必填，true 启用，false 禁用
     * @return 系统参数
     */
    @Override
    @Cacheable(value = "systemParameter",
            key = "#lookupCat+#lookupType+#enable",
            condition = "#lookupCat != null && #lookupType != null && #enable != null")
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)//不开启事务的支持
    public List<SysParameter> findByCondition(String lookupCat, String lookupType, Boolean enable) {
        Object result = sysParameterMapper.selectByCondition(lookupCat, lookupType, enable);
        return (List<SysParameter>) result;
    }
}
